package com.topscomm.mpm.script;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.IMpmProjectSaleService;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.mpm.utils.ConvertTimeUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

/**
 * @author wudaliang
 * @date 2021/1/19
 * @description:
 * @modify:
 */
public class MpmProjectReviewScript extends MpmProjectScript {

    /**
     * @author: wudaliang
     * @date: 2021-01-19
     * @param: service
     * @param: entity
     * @description: 项目复盘结束后更新
     * @return: void
     * @modify:
     */
    @Transactional
    public void projectReviewAfterApproval(ITapService service, TapEntity entity) throws Exception {
        //审批节点实例
        CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeins.getSourceid());
        MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil.getBean("mpmProjectService");
        MpmProjectSaleService mpmProjectSaleService  = (MpmProjectSaleService) SpringUtil.getBean("mpmProjectSaleService");
        MpmProjectReviewService mpmProjectReviewService = (MpmProjectReviewService) SpringUtil.getBean("mpmProjectReviewService");
        MpmProjectMilepostService mpmProjectMilepostService = (MpmProjectMilepostService) SpringUtil.getBean("mpmProjectMilepostService");
        MpmProjectTaskService mpmProjectTaskService = (MpmProjectTaskService) SpringUtil.getBean("mpmProjectTaskService");
        MpmProjectBidScoreService mpmProjectBidScoreService = (MpmProjectBidScoreService) SpringUtil.getBean("mpmProjectBidScoreService");
        //审批结束后，更新项目中的结项金额，项目状态，项目实际结项时间
        MpmProjectReviewEntity mpmProjectReviewEntity = mpmProjectReviewService.queryById(sourceId);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}'", mpmProjectReviewEntity.getProjectcode());
        List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
        MpmProjectEntity mpmProjectEntity = mpmProjectEntities.get(0);
        MpmProjectSaleEntity mpmProjectSaleEntity = mpmProjectSaleService.queryById(ConvertUtil.convertToString(mpmProjectEntity.getId()));
        Calendar calendar = Calendar.getInstance();
        //该状态是 项目状态的细粒度状态，只有在项目状态时“进行中”时，该状态才会有意义。
        // 这时候项目状态已从“进行中”变为“已结项”，所以将该状态置为无意义状态
        mpmProjectEntity.setSchedulestate(MpmSystemConst.MpmScheduleState.FrozenState);
        // 复盘结束后，将项目异常状态置为正常
        mpmProjectEntity.setAbnormalstate(0);
        //查询该项目下的任务
        List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
        sql.clear();
        sql.appendSingle("projectcode = '{0}' and enabled=1 ",mpmProjectReviewEntity.getProjectcode());
        //查询该项目下的里程碑及任务
        List<MpmProjectMilepostEntity> mpmProjectMilepostEntityList = mpmProjectMilepostService.queryByWhere(sql.toString());
        //1 ：异常结项     0：正常结项
        if("1".equals(ConvertUtil.convertToString(mpmProjectReviewEntity.getEndtype()))) {
            //异常结项
            mpmProjectEntity.setEndtype("1");
            mpmProjectEntity.setProjectendmoney(mpmProjectReviewEntity.getSettlementmoney());
            mpmProjectEntity.setProjectstate("8");
            mpmProjectEntity.setActualenddate(new Date());
            mpmProjectEntity.setAchievements(mpmProjectReviewEntity.getActualresult());
            // 把未达成的里程碑及任务的状态改为冻结，已达成的里程碑及任务状态不做变化
            for (MpmProjectMilepostEntity e : mpmProjectMilepostEntityList) {
                if (e.getMilepoststate() == 0) {
                    e.setMilepoststate(-1);
                    mpmProjectMilepostService.updateEntity(e);
                }
            }
            // 把未开始和进行中的任务状态改为冻结，已完成的任务的状态不做变化
            for (MpmProjectTaskEntity t : mpmProjectTaskEntities) {
                if (t.getTaskstate().equals("0") || t.getTaskstate().equals("1")) {
                    t.setTaskstate("-1");
                    mpmProjectTaskService.updateEntity(t);
                }
            }
        } else {
            //正常结项
            mpmProjectEntity.setEndtype("0");
            mpmProjectEntity.setProjectendmoney(mpmProjectReviewEntity.getSettlementmoney());
            mpmProjectEntity.setProjectstate("2");
            mpmProjectEntity.setActualenddate(new Date());
            mpmProjectEntity.setAchievements(mpmProjectReviewEntity.getActualresult());
        }
        // 如果销售项目的等级为A级且采购模式为“产品类招标”、“服务类招标”、“电商招标”，将复盘审批通过前一周作为会议结束时间
        if (MpmSystemConst.ProjectLevel.A.equals(mpmProjectEntity.getProjectlevel()) &&
                ( MpmSystemConst.PurchasePattern.chanpinBid.equals(mpmProjectSaleEntity.getPurchasepattern()) ||
                        MpmSystemConst.PurchasePattern.fuwuBid.equals(mpmProjectSaleEntity.getPurchasepattern()) ||
                        MpmSystemConst.PurchasePattern.dianshang.equals(mpmProjectSaleEntity.getPurchasepattern()) )   ) {
            // 获取7天之前的日期
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, -7);
            ConvertTimeUtil.convertToThisWeekSunday(calendar);
            mpmProjectEntity.setMeetenddate(calendar.getTime());
        }
        mpmProjectService.updateEntity(mpmProjectEntity);
        // 项目主表第三次自评记录
        mpmProjectBidScoreService.updateProjectBidScore(mpmProjectReviewEntity.getProjectcode(), MpmSystemConst.BidScoreTimes.thirdTime, mpmProjectReviewEntity.getQualityscore(), mpmProjectReviewEntity.getAbilityscore());
    }
    /**
     * @author: houyuhang
     * @date: 2022-11-28
     * @param: service
     * @param: entity
     * @description: 开始节点的结束脚本判断是否有投标部审批人
     * @return: void
     * @modify:
     */
    @Transactional
    public void bidApprovalUserReview(ITapService service, TapEntity entity) throws Exception {
        //审批节点实例
        CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
        String sourceId = ConvertUtil.convertToString(nodeins.getSourceid());
        MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil.getBean("mpmProjectService");
        MpmProjectReviewService mpmProjectReviewService = (MpmProjectReviewService) SpringUtil.getBean("mpmProjectReviewService");
        MpmProjectBidScoreFeedBackService mpmProjectBidScoreFeedBackService = (MpmProjectBidScoreFeedBackService) SpringUtil.getBean("mpmProjectBidScoreFeedBackService");
        MpmProjectSaleService mpmProjectSaleService = (MpmProjectSaleService) SpringUtil.getBean("mpmProjectSaleService");
        MpmProjectReviewEntity mpmProjectReviewEntity = mpmProjectReviewService.queryById(sourceId);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" projectcode = '{0}' ", mpmProjectReviewEntity.getProjectcode());
        MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
        if (ObjectUtil.isEmpty(mpmProjectEntity)) {
            return;
        }
        MpmProjectSaleEntity mpmProjectSaleEntity = mpmProjectSaleService.queryById(ConvertUtil.convertToString(mpmProjectEntity.getId()));
        if ((MpmSystemConst.ProjectLevel.A.equals(mpmProjectEntity.getProjectlevel()) || MpmSystemConst.ProjectLevel.B.equals(mpmProjectEntity.getProjectlevel()))
        && (MpmSystemConst.PurchasePattern.chanpinBid.equals(mpmProjectSaleEntity.getPurchasepattern()) || MpmSystemConst.PurchasePattern.fuwuBid.equals(mpmProjectSaleEntity.getPurchasepattern()) || MpmSystemConst.PurchasePattern.dianshang.equals(mpmProjectSaleEntity.getPurchasepattern()))) {
            List<String> userList = mpmProjectBidScoreFeedBackService.queryBidUserForBidScore(mpmProjectEntity);
            mpmProjectReviewEntity.setBidapprovaluser(userList.stream().collect(Collectors.joining(",")));
            mpmProjectReviewService.updateEntity(mpmProjectReviewEntity);
        }
    }
}
